/*
 *  Copyright 2019-2020
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.qp.basics.auth.service.impl;

import com.qp.basics.auth.repository.UserRepository2;
import com.qp.basics.auth.service.UserService2;
import com.qp.basics.common.domain.User;
import com.qp.basics.common.exception.EntityNotFoundException;
import com.qp.basics.common.service.dto.UserDto;
import com.qp.basics.common.service.mapstruct.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author
 * @date 2018-11-23
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "user")
public class UserService2Impl implements UserService2 {
    private final UserRepository2 userRepository;
    private final UserMapper userMapper;

    @Override
    @Cacheable(key = "'username:' + #p0 + ':' + T(com.qp.basics.common.datasource.DynamicDataSourceContextHolder).getDataSourceType()")
    public UserDto findByName(String userName) {
        User user = userRepository.findByUsername(userName);
        if (user == null) {
            throw new EntityNotFoundException(User.class, "name", userName);
        } else {
            return userMapper.toDto(user);
        }
    }
}
